package com.dataex.dbtool;

import java.util.Collection;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.LoggerFactory;

public class ImpJsonUtil {
	
	private static final org.slf4j.Logger logger = LoggerFactory	.getLogger(ImpJsonUtil.class);
	
	
	public interface CallBackIntface {
		public void eachJsonObj(JSONObject obj);		
	}
	
	static public long getLong(JSONObject obj, String key){
		if ( obj.has(key))
		{
			if ( obj.get(key) instanceof String )
			{
				try {
					return Long.parseLong(obj.getString(key));
				} catch (NumberFormatException e) {
					logger.info("parse to long failed, skip it, val:{}", obj.get(key));
					logger.info(""+e);
					return 0L;
				}
			}
			else
				return obj.getLong(key);
		}
		else
			return 0L;
	}
		
	static public JSONObject toJson(Object obj, CallBackIntface callBack ){
		JSONObject Jobj = JSONObject.fromObject(obj);
		if ( callBack != null  ){
			if ( Jobj instanceof JSONObject ){
				callBack.eachJsonObj(Jobj);
			}
		}
		return Jobj;
	}
	
	static public String getString(JSONObject obj, String key){
		if ( obj.has(key))
			return obj.get(key).toString();
		return "";
	}
	
	static public boolean getLongArr(JSONObject obj, String key, Collection<Long> varArr){
		if ( obj.has(key)){
			JSONArray arr = obj.getJSONArray(key);
			for ( int i=0; i<arr.size(); i++ ){
				if ( arr.get(i) instanceof String )
				{
					try {
						varArr.add(Long.parseLong(arr.getString(i)));
					} catch (NumberFormatException e) {
						logger.info("parse to long failed, skip it, val:{}", arr.get(i));
						logger.info(""+e);
					}
				}
				else
					varArr.add(arr.getLong(i));
			}

			return true;
		}
		else 
			return false;
	}
}
